package com.zbcz.erp.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.arouter.utils.TextUtils
import com.zbcz.erp.R
import com.zbcz.erp.adapter.CommonEditFileAdapter
import com.zbcz.erp.adapter.MyApplyToolsAdapter.Companion.MY_TOOLS_BEAN
import com.zbcz.erp.bean.BusinessAddBean
import com.zbcz.erp.bean.BusinessAddBean.Companion.BUSINESS_TRIP_REQUEST_DOC_TYPE
import com.zbcz.erp.bean.DoneJobBean
import com.zbcz.erp.bean.FileItem
import com.zbcz.erp.bean.MyToolsBean
import com.zbcz.erp.databinding.ActivityBusinessTripBinding
import com.zbcz.erp.fragment.CommonListFragment
import com.zbcz.erp.fragment.CommonListFragment.Companion.DONE_JOB_BEAN
import com.zbcz.erp.util.BUSINESS_TRIP_REQUEST_FORM
import com.zbcz.erp.util.DensityUtils
import com.zbcz.erp.util.IS_TEST_MODE
import com.zbcz.erp.util.ToastUtils
import com.zbcz.erp.util.UPLOAD_FORMAT_WHOLE
import com.zbcz.erp.util.compareDates
import com.zbcz.erp.util.formatDate
import com.zbcz.erp.util.onSingleClick
import com.zbcz.erp.util.showDatePickerDialog
import com.zbcz.erp.viewmodel.CommonRequestViewModel
import java.io.File

/**
 * 出差申请表
 */
@Route(path = BUSINESS_TRIP_REQUEST_FORM)
class BusinessTripRequestActivity : BaseActivity() {

    @Autowired(name = MY_TOOLS_BEAN)
    @JvmField
    var toolsBean: MyToolsBean? = null

    @Autowired(name = DONE_JOB_BEAN)
    @JvmField
    var mJobBean: DoneJobBean? = null

    @JvmField
    @Autowired
    var type: Int = 0

    private lateinit var mBinding: ActivityBusinessTripBinding

    private var mFormatStartTime: String? = null
    private var mFormatEndTime: String? = null

    private var mFileAdapter: CommonEditFileAdapter? = null
    private val mViewModel: CommonRequestViewModel by viewModels()

    companion object {
        const val TAG = "BusinessTripRequestActivity"
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        mBinding = ActivityBusinessTripBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        ARouter.getInstance().inject(this)
        init()
        initUploadInfos()
        super.onCreate(savedInstanceState)
    }

    private fun init() {
        mBinding.clTitle.tvTitle.text = "出差申请表"
        mBinding.clTitle.ivCommonBack.onSingleClick {
            finish()
        }
        mBinding.clParent.setPadding(
            0, DensityUtils.dp2px(this, 48f), 0, 0
        )
        mBinding.clTitle.ivCommonBack.onSingleClick {
            finish()
        }
        // 日期选择器
        mBinding.tvSelectStartTime.onSingleClick {
            showDatePickerDialog(this) { year, month, dayOfMonth ->
                mBinding.tvSelectStartTime.text = formatDate(year, month, dayOfMonth)
                mFormatStartTime = formatDate(year, month, dayOfMonth, UPLOAD_FORMAT_WHOLE)
                mBinding.tvSelectStartTime.setTextColor(
                    ContextCompat.getColor(
                        this@BusinessTripRequestActivity, R.color.black_text
                    )
                )
            }
        }

        mBinding.tvSelectEndTime.onSingleClick {
            showDatePickerDialog(this) { year, month, dayOfMonth ->
                mBinding.tvSelectEndTime.text = formatDate(year, month, dayOfMonth)
                mFormatEndTime = formatDate(year, month, dayOfMonth, UPLOAD_FORMAT_WHOLE)
                mBinding.tvSelectEndTime.setTextColor(
                    ContextCompat.getColor(
                        this@BusinessTripRequestActivity, R.color.black_text
                    )
                )
            }
        }

        // 初始化文件适配器
        mFileAdapter = CommonEditFileAdapter(this@BusinessTripRequestActivity)
        mBinding.rcFileList.adapter = mFileAdapter
        mFileAdapter?.submitList(listOf(FileItem(null, CommonEditFileAdapter.ADD_FILE_TYPE)))
        mBinding.tvConfirm.onSingleClick {
            val mTargetFile = mFileAdapter?.getTargetFile(this)
            onApplyConfirmClick(mTargetFile)
        }
        // 如果是测试模式，设置测试值
        if (IS_TEST_MODE) setTestValues()


        // 监听提交结果
        mViewModel.requestResult.observe(this) { pair ->
            if (pair.second == true) {
                ToastUtils.show("提交成功")
                finish()
            } else {
                ToastUtils.show(pair.first)
            }
        }

        mBinding.edInputRemark.addTextChangedListener {
            val textSize = it.toString().length
            mBinding.tvRemarkCount.text = "$textSize/300"
        }
        mBinding.tvCancel.onSingleClick{
            finish()
        }
    }

    private fun onApplyConfirmClick(file: File?) {
        if (mFormatStartTime == null) {
            ToastUtils.show("请选择开始时间")
            return
        }
        if (mFormatEndTime == null) {
            ToastUtils.show("请选择结束时间")
            return
        }
        if (compareDates(mFormatStartTime, mFormatEndTime, UPLOAD_FORMAT_WHOLE) >= 0) {
            ToastUtils.show("开始时间应当小于结束时间")
            return
        }
        if (TextUtils.isEmpty(mBinding.edInputPerson.text.toString())) {
            ToastUtils.show("请输入出行人员")
            return
        }

        if (TextUtils.isEmpty(mBinding.edInputReason.text.toString())) {
            ToastUtils.show("请输入出差事由")
            return
        }

        if (TextUtils.isEmpty(mBinding.edInputBusinessTarget.text.toString())) {
            ToastUtils.show("请输入出差行程")
            return
        }
        //if (toolsBean != null) toolsBean?.id else mJobBean.id
        val mAddBean = BusinessAddBean().apply {
            id = toolsBean?.id
            name = toolsBean?.name
            procDeTitle = toolsBean?.name
            procDefId = toolsBean?.id
            business_trip = mBinding.edInputBusinessTarget.text.toString()
            business_personnel = mBinding.edInputPerson.text.toString()
            business_reason = mBinding.edInputReason.text.toString()
            business_begin_date = mFormatStartTime
            business_end_date = mFormatEndTime
            business_airplane = if (mBinding.customRadioButton2.isChecked) "0" else "1"
            business_remarks = mBinding.edInputRemark.text.toString()
            filedNames = BUSINESS_TRIP_REQUEST_DOC_TYPE
            tableName = BusinessAddBean.TRAVEL_TABLE
        }
        setTestValues()
        mViewModel.createRequest(mAddBean, file)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ErpWorkProcessActivity.REQUEST_CODE_OPEN_DOCUMENT && resultCode == RESULT_OK) {
            data?.data?.let { fileUri ->
                Log.d(TAG, fileUri.toString())
                mFileAdapter?.addData(fileUri)
            }
        }
    }

    private fun setTestValues() {
        if (IS_TEST_MODE) {
            with(mBinding) {
                edInputReason.setText("reason")
                edInputPerson.setText("张三")
                edInputBusinessTarget.setText("北京")
                edInputRemark.setText("remark")
            }
        }
    }

    /**
     * 初始化上传信息
     */
    private fun initUploadInfos() {
        if (type == CommonListFragment.MY_TO_DO_LIST || type == CommonListFragment.MY_DONE_LIST || type == CommonListFragment.MY_APPLY || type == CommonListFragment.RE_APPLY) {
            if (type != CommonListFragment.RE_APPLY) {
                setFieldsEditable(false)
            }
            mViewModel.queryFormInfo(mJobBean?.tableId ?: "", mJobBean?.tableName ?: "")
            mViewModel.mQueryFormInfo.observe(this) { addBean ->
                populateFormFields(addBean)
                if (type == CommonListFragment.RE_APPLY) {
                    if (addBean != null) {
                        displayReApplyViews(addBean)
                    }
                }
            }

            when (type) {
                CommonListFragment.MY_TO_DO_LIST -> displayToDoViews()
                CommonListFragment.MY_DONE_LIST, CommonListFragment.MY_APPLY -> displayDoneViews()
                //MY_APPLY -> displayReApplyViews()
            }
        }
    }

    private fun displayToDoViews() {
        with(mBinding) {
            tvContentAdvice.visibility = View.VISIBLE
            edContentAdvice.visibility = View.VISIBLE
            tvAdviceCount.visibility = View.VISIBLE
            tvCancel.text = "驳回"
            tvConfirm.text = "同意"
            tvCancel.onSingleClick {
                onApplyConfirmClick(
                    mJobBean?.id ?: "", mJobBean?.procInstId ?: "", false
                )
            }
            tvConfirm.onSingleClick {
                onApplyConfirmClick(
                    mJobBean?.id ?: "", mJobBean?.procInstId ?: "", true
                )
            }

            mViewModel.mActPassLiveData.observe(this@BusinessTripRequestActivity) { result ->
                handleApprovalResult(result)
            }

            mViewModel.mActBackLiveData.observe(this@BusinessTripRequestActivity) { result ->
                handleRejectionResult(result)
            }

            edContentAdvice.addTextChangedListener { text ->
                val textSize = text.toString().length
                tvAdviceCount.text = "$textSize/100"
            }
        }
    }


    /**
     * 显示已完成视图
     */
    private fun displayDoneViews() {
        with(mBinding) {
            clBottomParent.visibility = View.GONE
            nsParent.setPadding(0, 0, 0, 0)
        }
    }

    private fun handleApprovalResult(result: Pair<Boolean, String?>) {
        if (result.first) {
            ToastUtils.show("审批通过")
            finish()
        } else {
            ToastUtils.show(result.second ?: "")
        }
    }

    /**
     * 处理驳回结果
     */
    private fun handleRejectionResult(result: Pair<Boolean, String?>) {
        if (result.first) {
            ToastUtils.show("驳回成功")
            finish()
        } else {
            ToastUtils.show(result.second ?: "")
        }
    }

    /**
     * 填充表单字段
     *     var business_reason: String? = ""//出差事由
     *     var business_personnel: String? = ""//出差人员
     *     var business_begin_date: String? = ""//出差开始日期
     *     var business_end_date: String? = ""//出差结束日期
     *     var business_trip: String? = ""//出差行程
     *     var business_airplane: String = ""//是否机票
     *     var business_file: String = ""//出差附件
     *     var business_remarks: String = ""//出差备注
     *
     */
    private fun populateFormFields(addBean: BusinessAddBean?) {
        with(mBinding) {
            if (addBean != null) {
                edInputReason.setText(addBean.business_reason)
                edInputPerson.setText(addBean.business_personnel)
                tvSelectStartTime.setText(addBean.business_begin_date)
                tvSelectEndTime.setText(addBean.business_end_date)
                edInputBusinessTarget.setText(addBean.business_trip)
                if (addBean.business_airplane != "1") {
                    customRadioButton2.isChecked = true
                } else {
                    customRadioButton1.isChecked = true
                }
                edInputRemark.setText(addBean.business_remarks)
                tvSelectStartTime.setTextColor(
                    ContextCompat.getColor(
                        this@BusinessTripRequestActivity, R.color.black_text
                    )
                )

                tvSelectEndTime.setTextColor(
                    ContextCompat.getColor(
                        this@BusinessTripRequestActivity, R.color.black_text
                    )
                )
            }
//            edInputSealCount.setText(addBean?.number_of_copies.toString())
//            edInputRemark.setText(addBean?.remarks)
//            edContentBrief.setText(addBean?.content_summary)
//            edInputResSealPerson.setText(addBean?.handler)
////            tvApplySealName.setText(addBean?.seal_name)
////            tvApplySealFileType.setText(addBean?.document_type.toString())
//            edInputSendUnit.setText(addBean?.recipient_unit)
//            //if (type != RE_APPLY) {
//            tvApplySealDate.text = formatDateTime(addBean?.seal_date ?: "")
//            //}
//            if (type != CommonListFragment.RE_APPLY) {
//                tvApplySealDate.onSingleClick {
//                    showDatePickerDialog(this@ApplyForSealActivity) { year, month, dayOfMonth ->
//                        tvApplySealDate.text = formatDate(year, month, dayOfMonth)
//                        mFormatTime = formatDate(year, month, dayOfMonth, UPLOAD_FORMAT_WHOLE)
//                        tvApplySealDate.setTextColor(
//                            ContextCompat.getColor(
//                                this@ApplyForSealActivity, R.color.black_text
//                            )
//                        )
//                    }
//                }
//            }
//            tvApplySealDate.setTextColor(
//                ContextCompat.getColor(
//                    this@ApplyForSealActivity, R.color.black_text
//                )
//            )

            if (type != CommonListFragment.RE_APPLY) {
                if (!TextUtils.isEmpty(addBean?.business_file)) {
                    mFileAdapter?.submitList(
                        listOf(
                            FileItem(
                                uri = null,
                                type = CommonEditFileAdapter.REMOTE_FILE_TYPE,
                                remoteUrl = addBean?.business_file ?: ""
                            )
                        )
                    )
                } else {
                    //tvFiles.visibility = View.GONE
                    fileGroup.visibility = View.GONE
                    rcFileList.visibility = View.GONE
                }
            } else {
                val mutableFileList =
                    mutableListOf(FileItem(null, CommonEditFileAdapter.ADD_FILE_TYPE))
                if (!TextUtils.isEmpty(addBean?.business_file)) {
                    mutableFileList.add(
                        FileItem(
                            uri = null,
                            type = CommonEditFileAdapter.REMOTE_FILE_TYPE,
                            remoteUrl = addBean?.business_file ?: "",
                            isDelAble = true
                        )
                    )
                }
                mFileAdapter?.submitList(mutableFileList)
            }
        }
    }

    /**
     * 设置字段是否可编辑
     */
    private fun setFieldsEditable(isEditable: Boolean) {
        with(mBinding) {
            edInputBusinessTarget.isEnabled = isEditable
            edInputBusinessTarget.isFocusable = isEditable
            edInputPerson.isFocusable = isEditable
            edInputPerson.isEnabled = isEditable
            edInputRemark.isEnabled = isEditable
            edInputRemark.isFocusable = isEditable
            edInputReason.isFocusable = isEditable
            edInputReason.isEnabled = isEditable
            tvSelectStartTime.isEnabled = isEditable
            tvSelectEndTime.isEnabled = isEditable
            radioGroup.isEnabled = false
            customRadioButton1.isEnabled = false
            customRadioButton2.isEnabled = false
        }
    }

    /**
     * 审批或驳回点击事件
     */
    private fun onApplyConfirmClick(id: String, procInstId: String, isPass: Boolean) {
        mViewModel.actPass(isPass, id, procInstId, mBinding.edContentAdvice.text.toString())
    }

    /**
     * 显示重新申请视图
     */
    private fun displayReApplyViews(addBean: BusinessAddBean) {
        // 实现重新申请视图显示逻辑
//        mBinding.tvApplySealDate.text = "请选择"
//        mBinding.tvConfirm.onSingleClick {
//            onReplyClick(addBean)
//        }
//        mBinding.tvCancel.onSingleClick {
//            finish()
//        }
    }


//    private fun onReplyClick(addBean: BusinessAddBean) {
//        if (mFormatTime.isNullOrEmpty()) {
//            ToastUtils.show("日期不能为空")
//            return
//        }
//        val mDate = mFormatTime
//        val mDocType = mBinding.spApplySealFileType.selectedItem
//        val mSendUnit = mBinding.edInputSendUnit.text.toString()
//        val mBrief = mBinding.edContentBrief.text.toString()
//        val mCount = mBinding.edInputSealCount.text.toString()
//        val mResSealPerson = mBinding.edInputResSealPerson.text.toString()
//        val mRemark = mBinding.edInputRemark.text.toString()
//        addBean.apply {
//            content_summary = mBrief
//            //seal_name = mName
//            createTime = mDate
//            //document_type = mFileType
//            recipient_unit = mSendUnit
//            number_of_copies = mCount
//            remarks = mRemark
//            seal_date = mDate
//            handler = mResSealPerson
//            file_handler = mResSealPerson
//        }
//        mViewModel.createEditRequest(addBean, mFileAdapter?.getTargetFile(this), mJobBean?.id)
//    }
}